package com.atguigu.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration //当前配置类也需要被扫描
@EnableWebSecurity //@EnableWebSecurity是开启SpringSecurity的默认行为(出现一个登录页面)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /*内存分配用户名密码
     * 无密码加密器时：springsecurity There is no PasswordEncoder mapped for the id "null"
     */

//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//                .withUser("weiranyi")
//                .password(new BCryptPasswordEncoder().encode("123456"))
//                .roles("");
//    }

    // 指定加密方式，上下加密方式要一致
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    // 默认Spring Security不允许iframe嵌套显示，我们需要设置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //允许iframe嵌套显示
        http.headers().frameOptions().disable();
        // 1.登录设置，采用自定义登录页面，注销功能等，不采用默认策略
        http.authorizeRequests()
                .antMatchers("/static/**", "/login").permitAll()  //允许匿名用户访问的路径
                .anyRequest().authenticated()    // 其它页面全部需要验证
        // 2.指定登录页面
                .and()
                .formLogin()
                .loginPage("/login") //表单页面的地址
                //.usernameParameter("username") // 如果省略，必须是username
                //.passwordParameter("password") //如果省略，必须是password
                .loginProcessingUrl("/login")  //提交表单的处理地址
                //.failureForwardUrl("/login") //登录失败后哪里
                .defaultSuccessUrl("/")//登录成功后哪里
        // 3.自定义的注销行为
                .and()
                .logout()
                .logoutUrl("/logout")   //退出登陆的路径，指定spring security拦截的注销url,退出功能是security提供的
                .invalidateHttpSession(true)
                .logoutSuccessUrl("/login")//用户退出后要被重定向的url

        // 4.取消CSRF(注销功能需要禁用TA) 框架搞定注销功能
                .and()
                .csrf().disable();//关闭跨域请求伪造功能
        //添加自定义无权限处理器
        http.exceptionHandling().accessDeniedHandler(new CustomAccessDeineHandler());
    }
}